import router from './router'
import NProgress from 'nprogress' // progress bar
import '@/components/NProgress/nprogress.less' // progress bar custom style
const MODULE_TAG = '/module/'
const MODULE_LOAD_TAG = 'pulling'
// http://localhost:8000/#/portal/module/mock-about/about-me
const resloveModuleUrl = (fullPath) => {
  const lazyUrl = fullPath.split(MODULE_TAG)[1]
  const portalUrl = fullPath.split(MODULE_TAG)[0]
  const moduleName = lazyUrl.split('/')[0]
  return {
    fullPath, moduleName, portalUrl, lazyUrl
  }
}
const isModuleMode = (url) => {
  return url.indexOf(MODULE_TAG) !== -1
}
NProgress.configure({ showSpinner: false }) // NProgress Configuration

router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  // 判断去往的路由是否存在与权限菜单中
  const url = to.fullPath
  if (url.indexOf(MODULE_LOAD_TAG) !== -1) {
    next()
  } else if (isModuleMode(url)) {
    const { moduleName, portalUrl, lazyUrl } = resloveModuleUrl(url)
    if (window[moduleName]) {
      next()
    } else {
      next({
        path: portalUrl + MODULE_TAG + moduleName + '/' + MODULE_LOAD_TAG,
        // replace: true,
        query: { lazyUrl }
      })
    }
  } else {
    next()
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
